﻿using System;
using ZhCun.SerialIO.Utils;

namespace SerialIoDemo.FixedHead.ProtocolModel
{
    /// <summary>
    /// 接收(读)串口数据的实体基类
    /// </summary>
    public abstract class R_Base : BaseProtocol
    {
        /// <summary>
        /// 解析数据对象
        /// </summary>
        protected BytesAnaly AnalyObj { get; private set; }
        /// <summary>
        /// 解析消息体, 0 正常, 1 校验码 错误，2 解析异常
        /// </summary>
        protected abstract int AnalyBody(BytesAnaly analy);

        /// <summary>
        /// 解析协议，
        /// 0 成功
        /// 1 校验码错误
        /// 9 异常
        /// </summary>
        public int Analy(byte[] data, int offset, int count)
        {
            try
            {
                var crc = GetCRC(data, offset, count - 2); //校验码方法内去除
                var crcBytes = BitConverter.GetBytes(crc);
                if (crcBytes[0] != data[offset + count - 1] || crcBytes[1] != data[offset + count - 2])
                {
                    return 1;
                }
                //[0xaa,0xbb] [len] [cmd] [DevId] [data] [crc-1,crc-2]
                AnalyObj = new BytesAnaly(data, offset, count, 4); // 跳过包头部分
                DevId = AnalyObj.GetByte(); // 取 DevId                
                var r = AnalyBody(AnalyObj);
                return r;
            }
            catch
            {
                //LogHelper.LogObj.Error($"解析数据包发生异常.", ex);
                return 9;
            }
        }
    }
}